package com.mpdbailey.cleverdicandroid;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.TextView;

import com.pigdogbay.androidutils.utils.ActivityUtils;

public class ResultsFragment extends ListFragment
{
	private boolean _CachedBusy = false;
	private String _CachedStatus = "";
	
	private Drawable busyBackground, okBackground;
	@Override
	public void onAttach(Activity activity)
	{
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		busyBackground = getResources().getDrawable(R.drawable.red_gradient);
		okBackground = getResources().getDrawable(R.drawable.blue_gradient);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.results_fragment, container, false); 
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{
		//Views and contexts have now been created 
		super.onActivityCreated(savedInstanceState);
		getListView().setOnItemLongClickListener(new OnItemLongClickListener()
		{
			public boolean onItemLongClick(AdapterView<?> arg0, View v,
					int position, long id)
			{
				try
				{
					String word = (String) getListAdapter().getItem(position);
					word = AnagramPresenter.RemoveFormatting(word);
					String url = getString(R.string.DictionaryURLTemplate)
							.replace("$WORD", word);
					ActivityUtils.ShowWebPage(getActivity(), url);
				} catch (Exception e)
				{
				}
				return true;
			}

		});
		setStatus(_CachedStatus, _CachedBusy);
	}

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	public void setStatus(String status, boolean busy)
	{
		FragmentActivity activity = getActivity();
		if (null==activity)
		{
			//Fragment is not yet ready so remember the settings for when it is
			_CachedBusy=busy;
			_CachedStatus=status;
			return;
		}
		TextView textStatus = (TextView)activity.findViewById(R.id.textStatus);
		textStatus.setText(status);
		Drawable background = null;
		if (!"".equals(status))
		{
			background = busy ? busyBackground : okBackground;
		}
		int sdk = android.os.Build.VERSION.SDK_INT;
		if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN)
		{
			textStatus.setBackgroundDrawable(background);
		} else
		{
			textStatus.setBackground(background);
		}
	}	

}
